package com.zzw.springboot.controller;

import com.zzw.springboot.config.RabbitMQConfig;
import com.zzw.springboot.util.RabbitMQUtil;
import com.zzw.springboot.util.Result;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * RabbitMQ监控控制器
 */
@RestController
@RequestMapping("/rabbitmq/monitor")
public class RabbitMQMonitorController {

    @Autowired
    private RabbitAdmin rabbitAdmin;

    @Autowired
    private RabbitMQUtil rabbitMQUtil;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 获取队列状态信息
     *
     * @return 队列信息
     */
    @GetMapping("/queue-status")
    public Result getQueueStatus() {
        Map<String, Object> result = new HashMap<>();

        try {
            // 使用RabbitAdmin获取队列属性
            Properties properties = rabbitAdmin.getQueueProperties(RabbitMQConfig.QUEUE_NAME);

            if (properties != null) {
                // 队列存在
                int messageCount = 0;
                if (properties.get("QUEUE_MESSAGE_COUNT") != null) {
                    messageCount = (int) properties.get("QUEUE_MESSAGE_COUNT");
                }

                int consumerCount = 0;
                if (properties.get("QUEUE_CONSUMER_COUNT") != null) {
                    consumerCount = (int) properties.get("QUEUE_CONSUMER_COUNT");
                }

                result.put("queueName", RabbitMQConfig.QUEUE_NAME);
                result.put("messageCount", messageCount);
                result.put("consumerCount", consumerCount);
                result.put("status", "active");

                return Result.success(result, "队列状态查询成功");
            } else {
                // 队列不存在
                return Result.error(404, "队列不存在：" + RabbitMQConfig.QUEUE_NAME);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(500, "查询队列状态失败: " + e.getMessage());
        }
    }

    /**
     * 重新创建队列和绑定
     */
    @GetMapping("/recreate-queue")
    public Result recreateQueue() {
        try {
            // 删除已有队列（如果存在）
            rabbitAdmin.deleteQueue(RabbitMQConfig.QUEUE_NAME);

            // 删除已有交换机（如果存在）
            rabbitAdmin.deleteExchange(RabbitMQConfig.EXCHANGE_NAME);

            // 重新创建队列
            Queue queue = new Queue(RabbitMQConfig.QUEUE_NAME, true);
            rabbitAdmin.declareQueue(queue);

            // 重新创建交换机
            DirectExchange exchange = new DirectExchange(RabbitMQConfig.EXCHANGE_NAME);
            rabbitAdmin.declareExchange(exchange);

            // 重新绑定
            Binding binding = new Binding(
                RabbitMQConfig.QUEUE_NAME,
                Binding.DestinationType.QUEUE,
                RabbitMQConfig.EXCHANGE_NAME,
                RabbitMQConfig.ROUTING_KEY,
                null
            );
            rabbitAdmin.declareBinding(binding);

            Map<String, Object> result = new HashMap<>();
            result.put("queueName", RabbitMQConfig.QUEUE_NAME);
            result.put("exchangeName", RabbitMQConfig.EXCHANGE_NAME);
            result.put("routingKey", RabbitMQConfig.ROUTING_KEY);

            return Result.success(result, "队列、交换机和绑定已重新创建");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(500, "重新创建队列失败: " + e.getMessage());
        }
    }

    /**
     * 清空指定队列中的消息
     */
    @GetMapping("/purge-queue/{queueName}")
    public Result purgeQueue(@PathVariable String queueName) {
        try {
            rabbitAdmin.purgeQueue(queueName, false);
            return Result.success(200, "队列 " + queueName + " 的消息已清空");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(500, "清空队列失败: " + e.getMessage());
        }
    }
}
